package com.baiyinet.ui;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiyinet.BuildConfig;
import com.baiyinet.R;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.util.Utils;
import com.baiyinet.util.webview.WebViewManager;
import com.github.ybq.android.spinkit.SpinKitView;

import java.util.List;


/**
 * @author J.Huang
 * @version 1.0
 * @since 16/11/14
 */

public abstract class BaseToolbarActivity extends AppCompatActivity implements ToolbarOwner.IToolbar {

    protected Toolbar mToolbar;
    protected TextView mToolbarTitle;
    protected View mToolbarBottomLine;

    protected ToolbarOwner mToolbarOwner;

    protected List<ToolbarOwner.MenuAction> mActionBarMenuActionList;

    protected RelativeLayout mLayoutWebView;

    protected WebViewManager mWebViewManager;
    private WebView webView;

    protected void setupUI(ToolbarOwner.IToolbar iToolbar) {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbarTitle = (TextView) findViewById(R.id.tv_toolbar_title);
        mToolbarBottomLine = findViewById(R.id.view_toolbar_bottom_line);

        if ("light".equals(BuildConfig.TOOLBAR_BACK)) {
            mToolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.white));
        } else {
            mToolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.toolbar_title));
        }

        if (BuildConfig.SHOW_TOOLBAR_BOTTOM_LINE) {
            mToolbarBottomLine.setVisibility(View.VISIBLE);
        } else {
            mToolbarBottomLine.setVisibility(View.GONE);
        }

        setSupportActionBar(mToolbar);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 按回退键后强制关闭输入法
                Utils.UI.closeInputMethod(BaseToolbarActivity.this);
                onBackPressed();
            }
        });

        mToolbarOwner = new ToolbarOwner(iToolbar);

        final SpinKitView loadingIndicator = (SpinKitView) findViewById(R.id.view_loading_indicator);

//        WebView webView = (WebView) findViewById(R.id.activity_webView);
        webView = new WebView(this.getParent() == null ? this : this.getParent());

//        if (webView != null) {
            mWebViewManager = new WebViewManager(this, this, webView, loadingIndicator, getCurrentUser(), getApiHelper());
            mWebViewManager.init();
//        } else {
//            mWebViewManager = null;
//        }

        mLayoutWebView = (RelativeLayout) findViewById(R.id.layout_webview);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        );

        mLayoutWebView.addView(webView,0,layoutParams);

        View view = View.inflate(this, R.layout.view_network_failed, null);
        view.setVisibility(View.GONE);
        mLayoutWebView.addView(view,1,layoutParams);

        if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
//            mLayoutWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

    abstract protected CurrentUser getCurrentUser();
    abstract protected ApiHelper getApiHelper();

    @Override
    protected void onResume() {
        super.onResume();
        if (mWebViewManager != null) {
            mWebViewManager.resume();
        }

        if (webView != null) {
            webView.resumeTimers();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebViewManager != null) {
            mWebViewManager.pause();
        }
        if (webView != null) {
            webView.pauseTimers();
        }
    }

    @Override
    protected void onStop() {
        if (mWebViewManager != null) {
            mWebViewManager.stop();
        }
        super.onStop();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        mToolbar = null;
        mToolbarTitle = null;
        mToolbarOwner = null;
        if (mLayoutWebView != null) {
            mLayoutWebView.removeAllViews();
        }

        if (mWebViewManager != null) {
            // mWebViewManager有this的引用，必须清空
            mWebViewManager.destroy();
            mWebViewManager = null;
        }

        if (mActionBarMenuActionList != null) {
            mActionBarMenuActionList.clear();
        }

        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mActionBarMenuActionList != null && mActionBarMenuActionList.size() > 0) {
            for (final ToolbarOwner.MenuAction menuAction : mActionBarMenuActionList) {
                menu.add(menuAction.title)
                        .setIcon(menuAction.icon)
                        .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)
                        .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                menuAction.action.call();
                                return true;
                            }
                        });
            }
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == android.R.id.home) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setToolbarTitle(CharSequence title) {
        if (getSupportActionBar() != null) {
            // 默认title居左，不使用
            getSupportActionBar().setTitle("");
            if (mToolbarTitle != null && title != null) {
                if (title.toString().contains("about:blank") ||
                        title.toString().contains("找不到网页")) {
                    title = "";
                }
                mToolbarTitle.setText(title);
            }
        }
    }

    @Override
    public String getToolbarTitle() {
        String title = "";

        if (getSupportActionBar() != null) {
            if (mToolbarTitle != null) {
                title = mToolbarTitle.getText().toString();
            }
        }

        return title;
    }

    /***
     * 使左上角程序图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标
     * 对应id为android.R.id.home，对应ActionBar.DISPLAY_SHOW_HOME
     * @param enabled
     */
    @Override
    public void setDisplayShowHomeEnabled(boolean enabled) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowHomeEnabled(false);
        }
    }

    /***
     *  给左上角图标的左边加上一个返回的图标。对应ActionBar.DISPLAY_HOME_AS_UP
     * @param enabled
     */
    @Override
    public void setUpButtonEnabled(boolean enabled) {
        if (getSupportActionBar() != null) {
            // setHomeButtonEnabled和setDisplayShowHomeEnabled共同起作用。
            // 如果setHomeButtonEnabled设成false，
            // 即使setDisplayShowHomeEnabled设成true，图标也不能点击
            getSupportActionBar().setDisplayHomeAsUpEnabled(enabled);
            // setHomeButtonEnabled 小于4.0版本的默认值为true; 但是在4.0及其以上是false
            // 该方法的作用：决定左上角的图标是否可以点击。没有向左的小图标。true: 图标可以点击; false: 不可以点击。
            getSupportActionBar().setHomeButtonEnabled(enabled);
        }
    }

    @Override
    public void setNavigationIcon(int resId) {
        if (getSupportActionBar() != null && resId != 0) {
            mToolbar.setNavigationIcon(resId);
        }
    }

    @Override
    public void setMenu(List<ToolbarOwner.MenuAction> menuActionList) {
        if (menuActionList != mActionBarMenuActionList) {
            mActionBarMenuActionList = menuActionList;
//            invalidateOptionsMenu();
        }
    }

    @Override
    public void setToolbarVisible(boolean visible) {
        if (getSupportActionBar() != null) {
            if (visible) {
                getSupportActionBar().show();
            } else {
                getSupportActionBar().hide();
            }
        }
    }

    @Override
    public void setToolbarColor(String hexColor) {
        if (getSupportActionBar() != null) {
            if (!TextUtils.isEmpty(hexColor)) {
                if (hexColor.startsWith("#")) {
                    hexColor = hexColor.substring(1);
                }

                if (hexColor.length() != 6 && hexColor.length() != 8) {
                    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.theme)));
                    return;
                }

                StringBuilder sb = new StringBuilder();
                sb.append("#");
                if (hexColor.length() == 6) {
                    sb.append("FF");
                    sb.append(hexColor);
                } else if (hexColor.length() == 8) {
                    sb.append(hexColor);
                }

                getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(sb.toString())));
            } else {
                getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.theme)));
            }
        }
    }
}
